class AudioPlayer {
  constructor () {
    this.audio = this.createAudio()
  }
  //  初始化播放器
  init (url) {
    this.audio.src = url
    this.audio.volume = 0.5
  }
  //  播放
  play () {
    this.audio.play()
  }
  //  暂停
  pause () {
    this.audio.pause()
  }
  // 是否播放结束
  ended () {
    return this.audio.ended
  }
  //  创建播放dom
  createAudio () {
    return document.createElement('audio')
  }
  //  设置音量
  setVolume (num) {
    this.audio.volume = num
  }
  //  设置当前播放时间
  setCurrentTime (num) {
    this.audio.currentTime = this.audio.duration * num
  }
  //  设置播放时间
  backPlay (num) {
    this.audio.currentTime += num
  }
  //  获取播放器音量
  getVolume () {
    return this.audio.volume
  }
  //  获取播放进度
  getAudioInfo (callBack) {
    const _this = this
    //  当播放器正在播放
    this.audio.oncanplaythrough = function () {
    //  获取播放器正在播放音频，总时长
      let nAllTime = Math.ceil(this.duration)
      let nMinute = _this.fillNumber(nAllTime / 60)
      let nSecond = _this.fillNumber(nAllTime % 60)
      //  获取播放器当前播放进度
      this.ontimeupdate = function () {
        let nCurentTime = _this.audio.currentTime
        let nCurentMinute = _this.fillNumber(nCurentTime / 60)
        let nCurentSecond = _this.fillNumber(nCurentTime % 60)
        let nProportion = nCurentTime / nAllTime
        callBack && callBack({ nMinute, nSecond, nCurentMinute, nCurentSecond, nProportion })
      }
    }
  }
  //  自动补0
  fillNumber (num) {
    return Math.floor(num) < 10 ? '0' + Math.floor(num) : Math.floor(num)
  }
  //  单例
  static getInstance () {
    let instance = null
    return function () {
      if (!instance) {
        instance = new AudioPlayer()
      }
      return instance
    }
  }
}
export default {
  //  挂在audio 到 vue原型
  install (Vue, options) {
    Vue.prototype.AudioPlayer = () => {
      return AudioPlayer
    }
  }
}
